import { createFileRoute } from '@tanstack/react-router'
import { AuthGuard } from '@/components/auth-guard'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { ChartContainer, ChartTooltip, ChartTooltipContent } from "@/components/ui/chart"
import { Bar, CartesianGrid, XAxis, Line, ComposedChart, YAxis } from "recharts"
import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Plus } from "lucide-react"
import { useAuth } from '@/providers/auth-provider'
import { weightService } from '@/services/weightService'
import type { WeightRecord, WeightStats } from '@/services/weightService'
import { toast } from 'sonner'
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import type { ChartConfig } from "@/components/ui/chart"

function useWeightData() {
    const chartConfig = {
        weight: {
            label: "体重 (kg)",
            color: "#71A3F4",
        },
    } satisfies ChartConfig

    return { chartConfig }
}

function WeightPage() {
    const { token } = useAuth()
    const [weightData, setWeightData] = useState<WeightRecord[]>([])
    const [weightStats, setWeightStats] = useState<WeightStats | null>(null)
    const [isLoading, setIsLoading] = useState(true)
    const [barSize, setBarSize] = useState(20)
    const [showRecordModal, setShowRecordModal] = useState(false)
    const [showSetupModal, setShowSetupModal] = useState(false)
    const [newWeight, setNewWeight] = useState('')
    const [recordDate, setRecordDate] = useState(new Date().toISOString().split('T')[0])
    const [height, setHeight] = useState('')
    const [targetWeight, setTargetWeight] = useState('')
    const { chartConfig } = useWeightData()
    const [setupRequired, setSetupRequired] = useState(false)

    useEffect(() => {
        const handleResize = () => {
            setBarSize(window.innerWidth < 768 ? 10 : 16)
        }
        
        handleResize()
        window.addEventListener('resize', handleResize)
        return () => window.removeEventListener('resize', handleResize)
    }, [])

    const checkSetupStatus = async () => {
        if (!token) return

        try {
            const statsResponse = await weightService.getWeightStats()
            
            if (!statsResponse.success && statsResponse.code === 500 && 
                statsResponse.message === "请先设置身高与理想体重") {
                setSetupRequired(true)
                setShowSetupModal(true)
                return false
            }
            
            if (statsResponse.success && statsResponse.data) {
                setWeightStats(statsResponse.data)
                return true
            }
            
            return false
        } catch (error) {
            return false
        }
    }

    const handleSetupInfo = async () => {
        if (!height || !targetWeight) {
            toast.error('请填写完整的信息')
            return
        }

        const heightNum = parseFloat(height)
        const targetWeightNum = parseFloat(targetWeight)
        
        if (isNaN(heightNum) || heightNum <= 0) {
            toast.error('请输入有效的身高')
            return
        }
        
        if (isNaN(targetWeightNum) || targetWeightNum <= 0) {
            toast.error('请输入有效的理想体重')
            return
        }

        try {
            const response = await weightService.setHeightAndTargetWeight({
                height: heightNum,
                targetWeight: targetWeightNum
            })

            if (response.success) {
                toast.success('设置成功')
                setShowSetupModal(false)
                setSetupRequired(false)
                await loadWeightData()
            } else {
                toast.error(response.message || '设置失败')
            }
        } catch (error) {
            toast.error('设置失败')
        }
    }

    const handleSaveWeight = async () => {
        if (!newWeight || !recordDate) {
            toast.error('请填写完整的体重信息')
            return
        }

        const weight = parseFloat(newWeight)
        if (isNaN(weight) || weight <= 0) {
            toast.error('请输入有效的体重数值')
            return
        }

        try {
            const response = await weightService.createWeightRecord({
                weight: weight.toFixed(2),
                date: recordDate
            })

            if (response.success) {
                toast.success('体重记录保存成功')
                setShowRecordModal(false)
                setNewWeight('')
                await loadWeightData()
            } else {
                toast.error(response.message || '保存失败')
            }
        } catch (error) {
            toast.error('保存体重记录失败')
        }
    }



    const loadWeightData = async () => {
        if (!token) return

        try {
            setIsLoading(true)
            
            const isSetupComplete = await checkSetupStatus()
            
            if (isSetupComplete) {
                const recordsResponse = await weightService.getWeightRecords()
                if (recordsResponse.success && recordsResponse.data) {
                    const recentRecords = recordsResponse.data.slice(-30).map((record: WeightRecord) => {
                        const weight = parseFloat(record.weight)
                        const sevenDayAvg = parseFloat(record.seven_day_average)
                        const dateStr = record.created_at || record.date
                        const formattedDate = dateStr ? dateStr.replace(' ', 'T') : new Date().toISOString()
                        return {
                            ...record,
                            weight: isNaN(weight) ? "0" : weight.toFixed(2),
                            seven_day_average: isNaN(sevenDayAvg) ? "0" : sevenDayAvg.toFixed(2),
                            date: formattedDate
                        }
                    })
                    setWeightData(recentRecords)
                }
            }
        } catch (error) {
        } finally {
            setIsLoading(false)
        }
    }

    useEffect(() => {
        loadWeightData()
    }, [token])

    if (isLoading) {
        return (
            <div className="p-2 md:p-4 lg:p-6 dark:bg-black min-h-screen">
                <Card className="border-gray-200 shadow-sm dark:bg-gray-900 dark:border-gray-700">
                    <CardHeader className="bg-gray-50/50 border-b border-gray-100 dark:bg-gray-800 dark:border-gray-600">
                    <div className="flex justify-between items-center">
                        <div>
                            <CardTitle className="text-gray-900 text-lg font-semibold dark:text-white">体重趋势</CardTitle>
                            <CardDescription className="text-gray-600 dark:text-gray-300">体重变化趋势图</CardDescription>
                        </div>
                        <Button 
                            className="bg-black hover:bg-gray-800 dark:bg-gray-700 dark:hover:bg-gray-600 text-white px-2 sm:px-3 py-2 rounded-lg transition-colors flex items-center gap-1 sm:gap-2"
                            onClick={() => {
                                if (setupRequired) {
                                    setShowSetupModal(true);
                                } else {
                                    setShowRecordModal(true);
                                }
                            }}
                        >
                            <Plus className="h-4 w-4" />
                            <span className="hidden sm:inline">记录体重</span>
                        </Button>
                    </div>
                </CardHeader>
                    <CardContent className="px-6 py-12">
                        <div className="text-center text-gray-500 dark:text-gray-400">
                            <p>加载中...</p>
                        </div>
                    </CardContent>
                </Card>
            </div>
        )
    }



    // 设置模态框 - 改为在主要内容中渲染而不是替换整个页面
    const renderSetupModal = () => {
        if (!setupRequired || !showSetupModal) return null;
        
        return (
            <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
                <Card className="w-full max-w-md mx-auto">
                    <CardHeader className="text-center">
                        <CardTitle className="text-2xl">设置身高与理想体重</CardTitle>
                        <CardDescription>请先设置您的身高和理想体重，以便更好地管理体重</CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-4">
                        <div className="space-y-2">
                            <Label htmlFor="height">身高 (cm)</Label>
                            <Input
                                id="height"
                                type="number"
                                placeholder="请输入身高"
                                value={height}
                                onChange={(e) => setHeight(e.target.value)}
                            />
                        </div>
                        <div className="space-y-2">
                            <Label htmlFor="targetWeight">理想体重 (kg)</Label>
                            <Input
                                id="targetWeight"
                                type="number"
                                step="0.1"
                                placeholder="请输入理想体重"
                                value={targetWeight}
                                onChange={(e) => setTargetWeight(e.target.value)}
                            />
                        </div>
                        <Button 
                            className="w-full bg-black hover:bg-gray-800 dark:bg-gray-700 dark:hover:bg-gray-600"
                            onClick={handleSetupInfo}
                        >
                            保存设置
                        </Button>
                    </CardContent>
                </Card>
            </div>
        )
    }

    // 如果没有数据且不在加载中，显示空状态
    if (!isLoading && weightData.length === 0) {
        return (
            <div className="p-2 md:p-4 lg:p-6 dark:bg-black min-h-screen">              
                <Card className="border-gray-200 shadow-sm dark:bg-gray-900 dark:border-gray-700">
                    <CardHeader className="bg-gray-50/50 border-b border-gray-100 dark:bg-gray-800 dark:border-gray-600">
                    <div className="flex justify-between items-center">
                        <div>
                            <CardTitle className="text-gray-900 text-lg font-semibold dark:text-white">体重趋势</CardTitle>
                            <CardDescription className="text-gray-600 dark:text-gray-300">体重变化趋势图</CardDescription>
                        </div>
                        <Button 
                            className="bg-black hover:bg-gray-800 dark:bg-gray-700 dark:hover:bg-gray-600 text-white px-2 sm:px-3 py-2 rounded-lg transition-colors flex items-center gap-1 sm:gap-2"
                            onClick={() => {
                                if (setupRequired) {
                                    setShowSetupModal(true);
                                } else {
                                    setShowRecordModal(true);
                                }
                            }}
                        >
                            <Plus className="h-4 w-4" />
                            <span className="hidden sm:inline">记录体重</span>
                        </Button>
                    </div>
                </CardHeader>
                    <CardContent className="px-6 py-12">
                        <div className="text-center text-gray-500 dark:text-gray-400">
                            <p className="mb-4">还没有体重记录</p>
                            <Button 
                                className="bg-black hover:bg-gray-800 dark:bg-gray-700 dark:hover:bg-gray-600"
                                onClick={() => {
                                    if (setupRequired) {
                                        setShowSetupModal(true);
                                    } else {
                                        setShowRecordModal(true);
                                    }
                                }}
                            >
                                添加第一条记录
                            </Button>
                        </div>
                    </CardContent>
                </Card>

                {/* 渲染设置模态框 */}
                {renderSetupModal()}

                {/* 记录体重模态框 */}
                {showRecordModal && (
                    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
                        <Card className="w-full max-w-md mx-auto">
                            <CardHeader>
                                <CardTitle>记录体重</CardTitle>
                                <CardDescription>记录您的体重变化</CardDescription>
                            </CardHeader>
                            <CardContent className="space-y-4">
                                <div className="space-y-2">
                                    <Label htmlFor="weight">体重 (kg)</Label>
                                    <Input
                                        id="weight"
                                        type="number"
                                        step="0.1"
                                        placeholder="请输入体重"
                                        value={newWeight}
                                        onChange={(e) => setNewWeight(e.target.value)}
                                    />
                                </div>
                                <div className="space-y-2">
                                    <Label htmlFor="date">日期</Label>
                                    <Input
                                        id="date"
                                        type="date"
                                        value={recordDate}
                                        onChange={(e) => setRecordDate(e.target.value)}
                                    />
                                </div>
                                <div className="flex gap-2">
                                    <Button 
                                        className="flex-1 bg-black hover:bg-gray-800 dark:bg-gray-700 dark:hover:bg-gray-600"
                                        onClick={handleSaveWeight}
                                    >
                                        保存
                                    </Button>
                                    <Button 
                                        variant="outline" 
                                        className="flex-1"
                                        onClick={() => setShowRecordModal(false)}
                                    >
                                        取消
                                    </Button>
                                </div>
                            </CardContent>
                        </Card>
                    </div>
                )}
            </div>
        )
    }

    return (
        <div className="p-2 md:p-4 lg:p-6 dark:bg-black min-h-screen">
            <Card className="border-gray-200 shadow-sm dark:bg-gray-900 dark:border-gray-700">
                <CardHeader className="bg-gray-50/50 border-b border-gray-100 dark:bg-gray-800 dark:border-gray-600">
                    <div className="flex justify-between items-center">
                        <div>
                            <CardTitle className="text-gray-900 text-lg font-semibold dark:text-white">体重趋势</CardTitle>
                            <CardDescription className="text-gray-600 dark:text-gray-300">体重变化趋势图</CardDescription>
                        </div>
                        <Button 
                            className="bg-black hover:bg-gray-800 dark:bg-gray-700 dark:hover:bg-gray-600 text-white px-2 sm:px-3 py-2 rounded-lg transition-colors flex items-center gap-1 sm:gap-2"
                            onClick={() => {
                                if (setupRequired) {
                                    setShowSetupModal(true);
                                } else {
                                    setShowRecordModal(true);
                                }
                            }}
                        >
                            <Plus className="h-4 w-4" />
                            <span className="hidden sm:inline">记录体重</span>
                        </Button>
                    </div>
                </CardHeader>
                <CardContent className="px-1 sm:px-2 md:px-4 lg:px-6">
                    {weightData.length > 0 ? (
                        <ChartContainer
                             config={chartConfig}
                             className="min-h-[300px] w-full h-full"
                         >
                            <ComposedChart data={weightData} margin={{ top: 20, right: 10, left: 0, bottom: 5 }}>
                                <CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" className="dark:stroke-gray-600" />
                                <XAxis
                                    dataKey="date"
                                    tickLine={false}
                                    tickMargin={10}
                                    axisLine={false}
                                    tickFormatter={(value) => {
                                        const date = new Date(value);
                                        return `${date.getMonth() + 1}/${date.getDate()}`;
                                    }}
                                    interval="preserveStartEnd"
                                />
                                <YAxis 
                                    tickLine={false} 
                                    axisLine={false} 
                                    tickMargin={10}
                                    domain={[0, 120]}
                                    ticks={[0, 20, 40, 60, 80, 100, 120]}
                                />
                                <ChartTooltip 
                                    content={<ChartTooltipContent labelFormatter={(value: any) => {
                                        const date = new Date(value);
                                        return date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' });
                                    }} />}
                                    cursor={{ fill: 'rgba(0,0,0,0.1)' }}
                                />
                                <Bar 
                                    dataKey="weight" 
                                    fill={chartConfig.weight.color} 
                                    radius={[2, 2, 0, 0]}
                                    maxBarSize={barSize}
                                />
                                <Line 
                                    type="monotone" 
                                    dataKey="seven_day_average" 
                                    stroke="#82ca9d" 
                                    strokeWidth={2}
                                    dot={false}
                                    name="7日均值"
                                />
                            </ComposedChart>
                        </ChartContainer>
                    ) : (
                        <div className="text-center py-12 text-gray-500">
                            <p>暂无数据显示</p>
                        </div>
                    )}
                </CardContent>
            </Card>

            <div className="grid md:grid-cols-3 gap-4 mt-6">
                <Card className="border-gray-200 shadow-sm dark:bg-gray-900 dark:border-gray-700">
                    <CardHeader className="bg-blue-50/50 border-b border-blue-100 dark:bg-blue-900/20 dark:border-blue-800">
                        <CardTitle className="text-blue-900 text-base font-medium dark:text-blue-100">当前体重</CardTitle>
                    </CardHeader>
                    <CardContent className="p-4">
                        <div className="text-2xl font-bold text-blue-600 dark:text-blue-400">
                            {weightStats?.current_weight ? `${weightStats.current_weight}kg` : '--'}
                        </div>
                    </CardContent>
                </Card>

                <Card className="border-gray-200 shadow-sm dark:bg-gray-900 dark:border-gray-700">
                    <CardHeader className="bg-green-50/50 border-b border-green-100 dark:bg-green-900/20 dark:border-green-800">
                        <CardTitle className="text-green-900 text-base font-medium dark:text-green-100">BMI指数</CardTitle>
                    </CardHeader>
                    <CardContent className="p-4">
                        <div className="text-2xl font-bold text-green-600 dark:text-green-400">
                            {weightStats?.bmi ? weightStats.bmi.bmi.toFixed(1) : '--'}
                            {weightStats?.bmi && (
                                <code className="ml-2 px-2 py-1 bg-gray-100 dark:bg-gray-700 rounded text-sm font-normal">
                                    {weightStats.bmi.category}
                                </code>
                            )}
                        </div>
                    </CardContent>
                </Card>

                <Card className="border-gray-200 shadow-sm dark:bg-gray-900 dark:border-gray-700">
                    <CardHeader className="bg-purple-50/50 border-b border-purple-100 dark:bg-purple-900/20 dark:border-purple-800">
                        <CardTitle className="text-purple-900 text-base font-medium dark:text-purple-100">理想体重</CardTitle>
                    </CardHeader>
                    <CardContent className="p-4">
                        <div className="text-2xl font-bold text-purple-600 dark:text-purple-400">
                            {weightStats?.target_weight ? `${weightStats.target_weight}kg` : '--'}
                        </div>
                    </CardContent>
                </Card>
            </div>

            {/* 渲染设置模态框 */}
            {renderSetupModal()}

            {/* 记录体重模态框 */}
            {showRecordModal && (
                <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
                    <Card className="w-full max-w-md mx-auto">
                        <CardHeader>
                            <CardTitle>记录体重</CardTitle>
                            <CardDescription>记录您的体重变化</CardDescription>
                        </CardHeader>
                        <CardContent className="space-y-4">
                            <div className="space-y-2">
                                <Label htmlFor="weight">体重 (kg)</Label>
                                <Input
                                    id="weight"
                                    type="number"
                                    step="0.1"
                                    placeholder="请输入体重"
                                    value={newWeight}
                                    onChange={(e) => setNewWeight(e.target.value)}
                                />
                            </div>
                            <div className="space-y-2">
                                <Label htmlFor="date">日期</Label>
                                <Input
                                    id="date"
                                    type="date"
                                    value={recordDate}
                                    onChange={(e) => setRecordDate(e.target.value)}
                                />
                            </div>
                            <div className="flex gap-2">
                                <Button 
                                    className="flex-1 bg-black hover:bg-gray-800 dark:bg-gray-700 dark:hover:bg-gray-600"
                                    onClick={handleSaveWeight}
                                >
                                    保存
                                </Button>
                                <Button 
                                    variant="outline" 
                                    className="flex-1"
                                    onClick={() => setShowRecordModal(false)}
                                >
                                    取消
                                </Button>
                            </div>
                        </CardContent>
                    </Card>
                </div>
            )}
        </div>
    )
}

export const Route = createFileRoute('/weight')({
    component: () => (
        <AuthGuard>
            <WeightPage />
        </AuthGuard>
    ),
})